#!/usr/bin/env bash

set -e -o pipefail

CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD`
MAIN_BRANCH="master"

if [[ "${CURRENT_BRANCH}" != "${MAIN_BRANCH}" ]]; then
  echo "scripts/publish-release must be run on the ${MAIN_BRANCH}."
  echo "Please checkout the ${MAIN_BRANCH} branch with:"
  echo "git checkout ${MAIN_BRANCH}"
  exit 1
fi

if !(command -v gh > /dev/null); then
  echo "GitHub CLI is required for this release script."
  echo "Please install GitHub CLI and try again:"
  echo "https://github.com/cli/cli#installation"
  exit 1
fi

# hostname is necessary just in case you are logged into the CLI
# GitHub enterprise instance
if !(gh auth status --hostname "github.com" > /dev/null 2>&1); then
  echo "Not logged into github".
  echo "Please run: gh auth login"
  exit 1
fi

git pull --rebase origin "${MAIN_BRANCH}"
# The --force overrides local tags.
# This is needed if you've published the CLI previously,
# otherwise git will exit with an error unnecessarily.
git fetch origin  --force --tags

PACKAGE_VERSION=`node -e "console.log(require('./lerna.json').version)"`
TAG_NAME="v${PACKAGE_VERSION}"
EXISTING_REMOTE_TAG=$(git ls-remote origin "refs/tags/${TAG_NAME}")

if [ -n "${EXISTING_REMOTE_TAG}" ]; then
  echo "The tag ${TAG_NAME} already exists on github.com"
  echo "This likely means this version has already been published."
  echo "Please examine the tag ${TAG_NAME} on github.com/heroku/cli to see the contents of the ${TAG_NAME} release"
  echo "You may need to run scripts/create-release-pr to create a new release before running this script"
  exit 1
fi

echo "Installing dependencies with yarn..."
yarn
echo "Done installing dependencies with yarn"

echo "publishing packages to npm..."
yarn lerna publish --yes from-package


LAST_PUBLISHED_TAG=$(git tag --sort="-version:refname" --list --format="%(refname:strip=2)" | head -n1)

git tag "${TAG_NAME}" -m "${TAG_NAME}"
git push origin "${TAG_NAME}"

RELEASE_NOTES=$(git log --graph --format="%h %s" "${LAST_PUBLISHED_TAG}...${TAG_NAME}~1")

gh release create "${TAG_NAME}" --title="${TAG_NAME}" --notes="${RELEASE_NOTES}"
